package com.bw.gmall.realtime.dwd.db.split.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.bw.gmall.realtime.common.base.BaseApp;
import com.bw.gmall.realtime.common.constant.Constant;
import com.bw.gmall.realtime.common.util.DateFormatUtil;
import com.bw.gmall.realtime.common.util.FlinkSinkUtil;
import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.FlatMapFunction;
import org.apache.flink.api.common.functions.RichMapFunction;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeinfo.TypeInformation;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.KeyedStream;
import org.apache.flink.streaming.api.datastream.SideOutputDataStream;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;
import org.apache.flink.util.OutputTag;

import java.time.Duration;

/**
 * @Author sw
 * @CreateTime 2024-11-15
 */
public class DwdBaseLog extends BaseApp {
    public static void main(String[] args) {
        new DwdBaseLog().start(10011,4, Constant.TOPIC_DWD_BASE_LOG,Constant.TOPIC_LOG);
    }

    @Override
    public void handle(StreamExecutionEnvironment env, DataStreamSource<String> dataStreamSource) {
        //1、ETL清洗数据
        SingleOutputStreamOperator<JSONObject> etlStream = etl(dataStreamSource);
        //2、添加水位线并keyby
        KeyedStream<JSONObject, String> keyedStream = getKeyedStream(etlStream);
        //3、新老用户校验
        SingleOutputStreamOperator<JSONObject> isNewStream = fixIsNew(keyedStream);
        //4、分流
        OutputTag<String> startTag = new OutputTag<String>("start", TypeInformation.of(String.class)); {};
        OutputTag<String> errTag = new OutputTag<String>("err", TypeInformation.of(String.class)); {};
        OutputTag<String> displaysTag = new OutputTag<String>("displays", TypeInformation.of(String.class)); {};
        OutputTag<String> actionsTag = new OutputTag<String>("actions", TypeInformation.of(String.class)); {};
        SingleOutputStreamOperator<String> splitStream = getSplitStream(isNewStream, startTag, errTag, displaysTag, actionsTag);
        //5、写入到kafka
        SideOutputDataStream<String> startStream = splitStream.getSideOutput(startTag);
        SideOutputDataStream<String> errStream = splitStream.getSideOutput(errTag);
        SideOutputDataStream<String> displaysStream = splitStream.getSideOutput(displaysTag);
        SideOutputDataStream<String> actionsStream = splitStream.getSideOutput(actionsTag);

        startStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_START));
        errStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ERR));
        displaysStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_DISPLAY));
        actionsStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_ACTION));
        splitStream.sinkTo(FlinkSinkUtil.getKafkaSink(Constant.TOPIC_DWD_TRAFFIC_PAGE));
    }

    /**
     * 4、分流
     * @param isNewStream
     * @param startTag
     * @param errTag
     * @param displaysTag
     * @param actionsTag
     * @return
     */
    private static SingleOutputStreamOperator<String> getSplitStream(SingleOutputStreamOperator<JSONObject> isNewStream, OutputTag<String> startTag, OutputTag<String> errTag, OutputTag<String> displaysTag, OutputTag<String> actionsTag) {
        return isNewStream.process(new ProcessFunction<JSONObject, String>() {
            @Override
            public void processElement(JSONObject jsonObject, ProcessFunction<JSONObject, String>.Context context, Collector<String> collector) throws Exception {
                JSONObject err = jsonObject.getJSONObject("err");
                JSONObject start = jsonObject.getJSONObject("start");
                JSONArray displays = jsonObject.getJSONArray("displays");
                JSONArray actions = jsonObject.getJSONArray("actions");
                JSONObject page = jsonObject.getJSONObject("page");
                JSONObject common = jsonObject.getJSONObject("common");
                Long ts = jsonObject.getLong("ts");
                if (err != null) {
                    context.output(errTag, err.toJSONString());
                    jsonObject.remove("err");
                }
                if (start != null) {
                    context.output(startTag, jsonObject.toJSONString());
                    jsonObject.remove("start");
                } else if (page != null) {
                    if (displays != null) {
                        for (int i = 0; i < displays.size(); i++) {
                            JSONObject display = displays.getJSONObject(i);
                            display.put("page", page);
                            display.put("common", common);
                            display.put("ts", ts);
                            context.output(displaysTag, display.toJSONString());
                        }
                        jsonObject.remove("displays");
                    }
                    if (actions != null) {
                        for (int i = 0; i < actions.size(); i++) {
                            JSONObject action = actions.getJSONObject(i);
                            action.put("page", page);
                            action.put("common", common);
                            action.put("ts", ts);
                            context.output(actionsTag, action.toJSONString());
                        }
                        jsonObject.remove("actions");
                    }
                    collector.collect(jsonObject.toJSONString());
                }
            }
        });
    }

    /**
     * 3、新老用户校验
     * @param keyedStream
     * @return
     */
    private static SingleOutputStreamOperator<JSONObject> fixIsNew(KeyedStream<JSONObject, String> keyedStream) {
        return keyedStream.map(new RichMapFunction<JSONObject, JSONObject>() {
            private ValueState<String> state;

            @Override
            public void open(Configuration parameters) throws Exception {
                state = getRuntimeContext().getState(new ValueStateDescriptor<String>("state", String.class));
            }

            @Override
            public JSONObject map(JSONObject jsonObject) throws Exception {
                //先取到is_new,判别先老用户
                JSONObject common = jsonObject.getJSONObject("common");
                String is_new = common.getString("is_new");
                Long ts = jsonObject.getLong("ts");
                //转成当前日期年月日，方便辨别状态，当天登录都属于新用户
                String curDate = DateFormatUtil.tsToDate(ts);
                //取出状态值对比
                String value = state.value();
                //如果是新用户，在判断是哪天登录
                if ("1".equals(is_new)) {
                    //如果状态有值且不是当天登录，修改为老用户，否则填充当前日期
                    if (value != null && !curDate.equals(value)) {
                        common.put("is_new", 0);
                    } else {
                        state.update(curDate);
                    }
                }
                return jsonObject;
            }
        });
    }

    /**
     * 2、添加水位线并keyby
     * @param etlStream
     * @return
     */
    private static KeyedStream<JSONObject, String> getKeyedStream(SingleOutputStreamOperator<JSONObject> etlStream) {
        return etlStream.assignTimestampsAndWatermarks(WatermarkStrategy
                .<JSONObject>forBoundedOutOfOrderness(Duration.ofSeconds(2))
                .withTimestampAssigner(new SerializableTimestampAssigner<JSONObject>() {
                    @Override
                    public long extractTimestamp(JSONObject jsonObject, long l) {
                        return jsonObject.getLong("ts");
                    }
                })).keyBy(new KeySelector<JSONObject, String>() {
            @Override
            public String getKey(JSONObject jsonObject) throws Exception {
                return jsonObject.getJSONObject("common").getString("mid");
            }
        });
    }

    /**
     * 1、ETL清洗数据
     * @param dataStreamSource
     * @return
     */
    private static SingleOutputStreamOperator<JSONObject> etl(DataStreamSource<String> dataStreamSource) {
        return dataStreamSource.flatMap(new FlatMapFunction<String, JSONObject>() {
            @Override
            public void flatMap(String s, Collector<JSONObject> collector) throws Exception {
                if (s != null) {
                    JSONObject jsonObject = JSON.parseObject(s);
                    JSONObject common = jsonObject.getJSONObject("common");
                    Long ts = jsonObject.getLong("ts");
                    if (common != null && ts != null) {
                        String mid = common.getString("mid");
                        if (mid != null && !"".equals(mid)) {
                            collector.collect(jsonObject);
                        }
                    }
                }
            }
        });
    }
}
